const { Message, User } = require('../models');
const fileUpload = require('../utils/fileUpload');
const path = require('path');

module.exports = {
  // 发送消息
  sendMessage: async (req, res) => {
    try {
      const { roomId, content } = req.body;
      const userId = req.user.id;

      let filePath = null;
      let fileType = null;

      // 处理文件上传
      if (req.file) {
        filePath = path.relative(path.join(__dirname, '../uploads'), req.file.path);
        fileType = req.file.mimetype.split('/')[0];
        if (fileType === 'application') fileType = 'document';
      }

      // 创建消息
      const message = await Message.create({
        content,
        roomId,
        userId,
        filePath,
        fileType
      });

      // 获取完整消息数据
      const fullMessage = await Message.findByPk(message.id, {
        include: [{
          model: User,
          attributes: ['id', 'username', 'avatar']
        }]
      });

      res.json(fullMessage);

      // 通过Socket.io广播消息
      req.io.to(roomId).emit('new_message', fullMessage);
    } catch (err) {
      res.status(500).json({ message: err.message });
    }
  },

  // 获取聊天室消息
  getMessages: async (req, res) => {
    try {
      const { roomId } = req.params;
      const { limit = 50, offset = 0 } = req.query;

      const messages = await Message.findAll({
        where: { roomId },
        order: [['createdAt', 'DESC']],
        limit: parseInt(limit),
        offset: parseInt(offset),
        include: [{
          model: User,
          attributes: ['id', 'username', 'avatar']
        }]
      });

      res.json(messages.reverse()); // 返回正序排列
    } catch (err) {
      res.status(500).json({ message: err.message });
    }
  },

  // 在 messageController.js 的 module.exports 中添加
  deleteMessage: async (req, res) => {
    try {
      const { id } = req.params;
      const userId = req.user.id;

      // 查找消息
      const message = await Message.findOne({
        where: { id }
      });

      // 验证消息是否存在
      if (!message) {
        return res.status(404).json({ message: 'Message not found' });
      }

      // 验证消息所有者（只有发送者可以删除）
      if (message.userId !== userId) {
        return res.status(403).json({ message: 'Unauthorized to delete this message' });
      }

      // 删除消息
      await message.destroy();

      // 通过Socket.io通知删除
      req.io.to(message.roomId).emit('delete_message', { id });

      res.json({ success: true, id });
    } catch (err) {
      res.status(500).json({ message: err.message });
    }
  },

  // 上传文件中间件
  uploadFile: fileUpload.single('file')
};